package com.tca.common.learning.datasource;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

/**
 * @author zhoua
 * @date 2024/1/6 11:55
 */
@Data
@AllArgsConstructor
public class DataSourceProxyHandler implements InvocationHandler {

    private static final String CLOSE_METHOD_NAME = "close";

    private static final String EQUALS_METHOD_NAME = "equals";

    /**
     * 目标Connection
     */
    private Connection objectConnection;

    /**
     * 数据源
     */
    private CustomDataSource dataSource;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 只会代理close方法, 其他方法不用代理
        String methodName = method.getName();
        if (CLOSE_METHOD_NAME.equalsIgnoreCase(methodName)) {
            dataSource.doReturn((Connection) proxy);
            return null;
        }
        // 调用equals方法时, 使用目标对象的equals, 同时需要将入参的代理对象转成目标对象
        if (EQUALS_METHOD_NAME.equalsIgnoreCase(methodName)) {
            return method.invoke(objectConnection,
                    ((DataSourceProxyHandler)Proxy.getInvocationHandler(args[0])).getObjectConnection());
        } else {
            return method.invoke(objectConnection, args);
        }

    }


}
